/**
 * 扬尘设备数据展示dustDeviceDataShow.js
 * 版本号： v1.0.0
 */
$(function () {
    //设置body宽度，避免样式变形
    var width = document.body.offsetWidth;
    if(width < 1100){
        width = 1150;
    }
    $('#dustDataShowBody_').width(width);

    var deviceNumber = $('#deviceId_').text();
    var deviceName= $('#deviceName_').text();
    if(deviceNumber != "无"){
        nowDataStandard(deviceNumber,deviceName);
    }else{
        var aqiImg = '<img src="'+ CONTEXT_PATH +'/html/images/dust/pieChart.jpg" style="width: 70%;height: 75%;margin-top: 30px;margin-left: 50px;border-radius: 50%;">'
        $('#aqiPieChart_').html(aqiImg);
    }
});


/**
 * 扬尘设备型号选择事件
 * @param device
 */
function deviceClick(device) {
    //获取扬尘设备型号
    var deviceNumber = $('.deviceNumberInner', device).text();
    //获取扬尘设备名称
    var deviceName = $('.deviceAreaInner', device).text();
    //历史数据扬尘时间单位置为时
    $(".timeBgStyle").css("background-color","#FFFFFF");
    $("#hour_").css("background-color","skyblue");
    //历史数据扬尘类型置为aqi
    $(".dustTypeLi").css("background-color","#FFFFFF");
    $("#aqi").css("background-color","skyblue");
    nowDataStandard(deviceNumber,deviceName);
}


/**
 * 更新数据
 * @param deviceId
 * @param deviceArea
 */
var getDataTimer = "";
function nowDataStandard(deviceNumber,deviceName){
    //更新设备型号
    $('#deviceId_').text(deviceNumber);
    //更新设备名称
    $('#region_').text(deviceName);
    //更新历史数据扬尘指标
    var startTime = "";
    var endTime = "";
    var resample = "H";
    var dustType = "aqi";
    dustTypeEchart(deviceNumber,startTime,endTime,resample,dustType);
    //每十秒轮询查询各指标实时数据以及警报数据
    pollingData(deviceNumber);
    //清除已存在的定时
    if(getDataTimer != ""){
        clearInterval(getDataTimer);
    }
    getDataTimer = setInterval(function(){pollingData(deviceNumber);}, 10000);
}

/**
 * 扬尘指标及以及警报数据
 */
function pollingData(deviceNumber){
    //各个设备aqi数据
    var deviceArr = document.getElementsByClassName('installedDevice');
    for(var i=0;i<deviceArr.length;i++){
        var deviceId = $('.deviceNumberInner', deviceArr[i]).text();
        $.ajax({
            url: CONTEXT_PATH + "/apiUtil/doGet.do",
            data: {
                url: "http://store.d.guijianyun.com:8000/devices/" + deviceId + "/latest"
            },
            type: "get",
            success: function (data) {
                if (data) {
                    var jsonObj = eval('(' + data + ')');
                    if(!jsonObj.data){
                        setDeviceAqi("","",deviceId);
                        return;
                    }
                    var pm25 = jsonObj.data.pm25;
                    if(pm25 == "undefined" || pm25 == ""){
                        setDeviceAqi("","",deviceId);
                    }else{
                        var aqi = calc_aqi(pm25);
                        var aqiLevel = cacl_aqiLevle(aqi);
                        setDeviceAqi(aqi,aqiLevel,deviceId);
                    }
                }else{
                    setDeviceAqi("","",deviceId);
                }
            },
            error:function () {
                setDeviceAqi("","",deviceId);
            }
        })
    }
    //扬尘实时数据
    var dustStandValErr = ["","","","","","","","","",""];
    $.ajax({
        url: CONTEXT_PATH + "/apiUtil/doGet.do",
        data: {
            url: "http://store.d.guijianyun.com:8000/devices/"+deviceNumber+"/latest"
        },
        type: "get",
        success: function (data) {
            if (data) {
                var jsonObj =  eval('(' + data + ')');
                if(null == jsonObj.data){
                    refNowData(dustStandValErr,"","");
                    return;
                }
                //最近更新时间
                var date = new Date(jsonObj.created_at);
                var localeString = date.toLocaleString('en-CHS', { hour12: false });
                date = localeString;
                //计算风向
                var wsLevel = "";
                try {
                    var ws = parseFloat(jsonObj.data.ws);
                    if(ws >= 0 && ws < 90) {
                        wsLevel = '南';
                    }else if(ws >= 90 && ws < 180) {
                        wsLevel = '西';
                    }else if(ws >= 180 && ws < 270) {
                        wsLevel = '北';
                    }else if(ws >= 270 && ws < 360) {
                        wsLevel = '东';
                    }
                }catch(err){

                }
                //计算大气压
                var pa = parseInt(jsonObj.data.pa/100);
                var dustStandValCor = [jsonObj.data.pm10+"",jsonObj.data.pm25+"",jsonObj.data.zs+"",jsonObj.data.wd+"",
                    jsonObj.data.tmp+"",jsonObj.data.rh+"",jsonObj.data.wp+"",wsLevel,pa+"",jsonObj.data.tsp+""];
                refNowData(dustStandValCor,jsonObj.data.pm25,date);
            }
        },
        error:function () {
            refNowData(dustStandValErr,"","");
        }
    });
    //扬尘警报
    $.ajax({
        url: CONTEXT_PATH + "/dustDeviceDataShow/dustAlarm.do",
        data: {
            deviceId: deviceNumber
        },
        type: "get",
        success: function (data) {
            $(".alarm-table").find("tr").each(function() {
                if($(this).attr("class") == "alarm-args"){
                    $(this).remove();
                }
            });
            if(data && data[0] && data[0].alarmTime){
                if(data.length > 0){
                    for(var i = 0; i < data.length; i++){
                      var newTr = '<tr class="alarm-args">'+
                                      '<td>'+data[i].alarmContent+'</td>'+
                                      '<td>'+data[i].alarmTime+'</td>'+
                                      '<td>'+data[i].alarmStatus+'</td>'+
                                  '</tr>';
                        $(".alarm-table").append(newTr);
                    }
                }
            }
        }
    })
}

/**
 * 设置扬尘设备aqi及aqi等级
 * @param aqi
 * @param aqiLevel
 * @param deviceId
 */
function setDeviceAqi(aqi,aqiLevel,deviceId){
    if(aqi == ""){
        aqi = "0";
    }
    if(aqiLevel == ""){
        aqiLevel = "无";
    }
    $('#aqi'+deviceId).text(aqi);
    $('#aqiLevel'+deviceId).text(aqiLevel);
}

/**
 * 更新实时数据
 * @param dustStandValArr
 */
function refNowData(dustStandValArr,pm25,date){
    //更新数据时间
    $('#updateTime_').text(date==""?"无":date);
    //更新aqi饼图
    var calAqi = 0;
    if(pm25 != "" && pm25 !="undefined"){
        calAqi = calc_aqi(pm25);
    }
    getAqiMeter(calAqi);
    //更新实时数据扬尘指标
    refDustStand(dustStandValArr);
}

/**
 * 更新扬尘指标
 * @param dustStandValArr
 */
function refDustStand(dustStandValArr){
    var nowDataDiv = "<div style='font-size:16px;margin-top:5px'>无</div>";
    var dustStandIdArr = ["pm10Value_","pm25Value_","zsValue_","wdValue_","tmpValue_","rhValue_","wpValue_","wsValue_","paValue_","pm100_"];
    for(var i=0;i<dustStandValArr.length;i++){
        if(dustStandValArr[i]==""||dustStandValArr[i]==null||dustStandValArr[i]=="undefined"){
            $('#'+dustStandIdArr[i]).html(nowDataDiv);
        }else{
            $('#'+dustStandIdArr[i]).html(dustStandValArr[i]);
        }
    }
}

/**
 * 历史数据：时间选择事件
 * @param times
 */
function timeSelect(times){
    $(".timeBgStyle").css("background-color","#FFFFFF");
    times.style.background="skyblue";
    var timeType = times.getAttribute("id");
    //获取聚合单位
    var resample = getResample(timeType);
    //扬尘设备编号
    var deviceNumber = $('#deviceId_').text();
    //时间选择框所选的开始与结束时间
    var startTime = $('#startTime_').datetimebox('getValue');
    var endTime = $('#endTime_').datetimebox('getValue');
    //获取选中的扬尘类型
    var dustTypeArr = document.getElementsByClassName('dustTypeLi');
    var dustType= "";
    for(var i=0;i<dustTypeArr.length;i++){
        var bg = dustTypeArr[i].style['background-color'];
        if(bg == "skyblue"){
            dustType = dustTypeArr[i].getAttribute("id");
        }
    }
    dustTypeEchart(deviceNumber,startTime,endTime,resample,dustType);
}

/**
 * 历史数据：扬尘类型选择事件
 * @param dustType
 */
function dustTypeSelect(dustType) {
    $(".dustTypeLi").css("background-color","#FFFFFF");
    dustType.style.background="skyblue";
    var dustTypeId = dustType.getAttribute("id");
    var deviceNumber = $('#deviceId_').text();
    //更新历史数据中的标题
    var stanardTitle = getStandardTitle(dustTypeId);
    $('#standardTitle_').text(stanardTitle);
    if(deviceNumber != "无" && deviceNumber != ""){
        //时间选择框所选的开始与结束时间
        var startTime = $('#startTime_').datetimebox('getValue');
        var endTime = $('#endTime_').datetimebox('getValue');
        //获取选中的扬尘类型
        var timeIdArr = document.getElementsByClassName('timeBgStyle');
        //默认为小时
        var timeType= "hour_";
        for(var i=0;i<timeIdArr.length;i++){
            var bg = timeIdArr[i].style['background-color'];
            if(bg == "skyblue"){
                timeType = timeIdArr[i].getAttribute("id");
            }
        }
        var resample = getResample(timeType);
        dustTypeEchart(deviceNumber,startTime,endTime,resample,dustTypeId);
    }
}

/**
 * 根据时间id获取聚合单位
 * @param timeType
 * @returns {string}
 */
function getResample(timeType){
    var resample = "";
    switch (timeType) {
        case "second_":
            resample = "S";
            break;
        case "minute_":
            resample = "T";
            break;
        case "hour_":
            resample = "H";
            break;
        case "day_":
            resample = "D";
            break;
        case "weekend_":
            resample = "W";
            break;
        case "month_":
            resample = "M";
            break;
        case "year_":
            resample = "Y";
            break;
    }
    return resample;
}

/**
 * 获取历史数据标题
 * @param type
 */
function getStandardTitle(type){
    var standardTitle = "";
    switch (type) {
        case "aqi":
            standardTitle = "空气质量指数AQI走势";
            break;
        case "pm25":
            standardTitle = "空气质量指数PM2.5走势";
            break;
        case "pm10":
            standardTitle = "空气质量指数PM10走势";
            break;
        case "tsp":
            standardTitle = "空气质量指数PM100走势";
            break;
        case "wd":
            standardTitle = "环境风速走势";
            break;
        case "tmp":
            standardTitle = "环境温度走势";
            break;
        case "rh":
            standardTitle = "环境湿度走势";
            break;
        case "zs":
            standardTitle = "环境噪声走势";
            break;
        case "wp":
            standardTitle = "环境风力走势";
            break;
    }
    return standardTitle;
}

/**
 * aqi计算
 * @param val
 * @returns {*}
 */
function calc_aqi(val){
    var ti = [0, 50, 100, 150, 200, 300, 400, 500]
    var tv = [0, 35, 75, 115, 150, 250, 350, 500]

    var i = 0;

    for (i in tv) {
        if (val < tv[i]) {
            break;
        }
        i = i + 1
        if (i == 7)
            return 600;
    }

    i = val/tv[i]*ti[i];
    return i.toFixed(2);
}

/**
 * aqi优良等级饼图
 * @param aqiData
 */
function getAqiMeter(aqiData){
    var aqiRank = cacl_aqiLevle(aqiData);
    var myChart = echarts.init(document.getElementById('aqiPieChart_'));
    window.addEventListener("resize", function () {
        myChart.resize();
    });
    var option = {
        title: {
            x: "32%",
            bottom: 25,
            text: '空气污染指数AQI',
            textStyle: {
                fontWeight: 'normal',
                fontSize: 15,
                color: "#0f0f0f"
            },
        },
        tooltip: {
            formatter: "{a} <br/>{b} : {c}"
        },
        series: [{
            min: 0,
            max: 500,
            axisLine: {
                width: 20,
                show: true,
                lineStyle: {
                    width: 30,
                    shadowBlur: 0,
                    color: [
                        [0.1, '#3CB371'],
                        [0.2, '#7CFC00'],
                        [0.3, '#ADFF2F'],
                        [0.4, '#FFA500'],
                        [0.6, '#FFFF00'],
                        [1, '#FF2776']
                    ]
                }
            },
            name: 'AQI',
            type: 'gauge',
            axisTick: {
                splitNumber: 30
            },
            //detail: {formatter:'{value}%'},
            detail: {
                formatter: "{value}",
                offsetCenter: [0, "60"],
                textStyle: {
                    fontSize: 25,
                    color: "#5BB1EF"
                }
            },
            data: [{
                value: aqiData,
                name: aqiRank
            }]
        }]
    };
    myChart.setOption(option);
}

/**
 * 计算aqi等级
 * @param aqiData
 */
function cacl_aqiLevle(aqiData){
    var aqiRank = "";
    switch (true) {
        case aqiData > 0 && aqiData <= 50:
            aqiRank = "优";
            break;
        case aqiData <= 100 && aqiData > 50:
            aqiRank = "良";
            break;
        case aqiData <= 150 && aqiData > 100:
            aqiRank = "轻度";
            break;
        case aqiData <= 200 && aqiData > 150:
            aqiRank = "中度";
            break;
        case aqiData <= 300 && aqiData > 200:
            aqiRank = "重度";
            break;
        case aqiData <= 500 && aqiData > 300:
            aqiRank = "严重";
            break;
        default:aqiRank = "无";
    }
    return aqiRank;
}

/**
 * 扬尘各类型数据图形化
 * @param deviceId
 * @param startTime
 * @param endTime
 * @param resample
 */
function dustTypeEchart(deviceNumber,startTime,endTime,resample,value) {
    //扬尘历史值url
    var dustUrl = "http://store.d.guijianyun.com:8000/service/calc?";
    var params = "device_id=" + deviceNumber;
    var start = "";
    //开始时间为空，获取当天0点的毫秒数作为开始时间
    if(startTime == null || startTime == ""){
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth()+1;
        var day = date.getDate();
        var startDate= new Date(year+"/"+month+"/"+day);
        start = startDate.getTime();
    }else{
        start = (new Date(startTime)).getTime();
    }
    if(endTime == null || endTime == ""){
        params = params + "&start=" + start + "&resample=" + resample;
    }else{
        var endTimeHs = (new Date(endTime)).getTime();
        params = params + "&start=" + start + "&end=" + endTimeHs + "&resample=" + resample;
    }
    var dustType = "";
    if(value=="aqi"){
        dustType="pm25";
    }else{
        dustType = value;
    }
    params = params + "&value=" + dustType;
    dustUrl = dustUrl + params;
    $.ajax({
        url: CONTEXT_PATH + "/apiUtil/doGet.do",
        data: {
            url: dustUrl
        },
        type: "get",
        success: function (data) {
            if(data) {
                var jsonObj = eval('(' + data + ')');
                if(jsonObj){
                    var timeArr = [];
                    var dataArr = [];
                    if(value == "aqi"){
                        for(var time in jsonObj){
                            var newTime = new Date(parseInt(time));
                            var timeData = calDateType(newTime,resample);
                            var paramVal = jsonObj[time];
                            if(paramVal == null){
                                dataArr.push(null)
                            }else{
                                var aqi = calc_aqi(paramVal);
                                dataArr.push(Number(aqi).toFixed(2));
                            }
                            timeArr.push(timeData);
                        }
                    }else{
                        for(var time in jsonObj){
                            var newTime = new Date(parseInt(time));
                            var timeData = calDateType(newTime,resample);
                            timeArr.push(timeData);
                            dataArr.push(Number(jsonObj[time]).toFixed(2));
                        }
                    }
                    getDstTypeEchart(value,timeArr,dataArr);
                }
            }else{
                getDstTypeEchart(value,new Array(),new Array());
            }
        },
        error:function () {
            getDstTypeEchart(value,new Array(),new Array());
        }
    });
}

/**
 * 计算时间类型
 * @param time
 * @param type
 */
function calDateType(time,type){
    var timeVal = "";
    var year = time.getFullYear();
    var month = time.getMonth()+1;
    var day = time.getDate();
    var hour = time.getHours();
    var minute = time.getMinutes();
    var second = time.getSeconds();
    switch(type){
        case "S":
            timeVal = hour + ":" + minute + ":" + second;
            break;
        case "T":
            timeVal = hour + ":" + minute;
            break;
        case "H":
            timeVal = hour;
            break;
        case "D":
            timeVal = day;
            break;
        case "W":
            timeVal = month + "-" + day;
            break;
        case "M":
            timeVal = month;
            break;
        case "Y":
            timeVal = year;
            break;
    }
    return timeVal;
}

/**
 * 获取历史数据统计图
 * @param title
 * @param xData
 * @param yData
 */
function getDstTypeEchart(dystType,xData,yData){
    //重定图形y轴值
    var yMax = 1;
    var yMaxValue = findMaxYdata(yData);
    var standardTitle = "";
    var unit = "";
    switch (true) {
        case dystType=="aqi" || dystType=="pm25" || dystType=="pm10" || dystType=="tsp":
            if(yMaxValue < 100){
                yMax = 100;
            }else if(yMaxValue >= 100 && yMaxValue < 200){
                yMax = 200;
            }else{
                yMax = 500;
            }
            unit = "ug/m3";
            standardTitle = dystType;
            break;
        case dystType=="wd":
            if(yMaxValue < 5){
                yMax = 5;
            }else if(yMaxValue >= 5 && yMaxValue < 20){
                yMax = 20;
            }else{
                yMax = 50;
            }
            unit = "m/s";
            standardTitle = "风速";
            break;
        case dystType=="tmp":
            if(yMaxValue < 20){
                yMax = 20;
            }else{
                yMax = 70;
            }
            unit = "℃";
            standardTitle = "温度";
            break;
        case dystType=="rh":
            if(yMaxValue < 20){
                yMax = 20;
            }else{
                yMax = 100;
            }
            unit = "%";
            standardTitle = "湿度";
            break;
        case dystType=="zs":
            if(yMaxValue < 40){
                yMax = 40;
            }else{
                yMax = 100;
            }
            unit = "db";
            standardTitle = "噪声";
            break;
        case dystType=="wp":
            if(yMaxValue < 5){
                yMax = 5;
            }else{
                yMax = 10;
            }
            unit = "级";
            standardTitle = "风力";
            break;
    }
    //构建图形
    var myChart1 = echarts.init(document.getElementById('dustTypeEchart_'));
    window.addEventListener("resize", function () {
        myChart1.resize();
    });
    var option = {
        toolbox: {
            right: 27,
            feature: {
                magicType: {
                    type: ['line', 'bar']
                }
            }
        },
        grid:{
            x:20,
            y:40,
            x2:45,
            y2:20,
            show:true,  //表示开启
            containLabel:50,
        },
        xAxis: {
            data: xData,
            splitLine: {
                lineStyle: {
                    color: '#D4DFF5'
                }
            },
            axisLine: {
                lineStyle: {
                    color: '#289bd3',
                    width: 2
                }
            },
            axisLabel: {
                textStyle: {
                    fontSize: 14,
                    color: '#333'
                }
            }
        },
        yAxis: {
            name: '单位('+unit+')',
            nameTextStyle:{
                padding:[3, 4, 5, 40]
            },
            axisLine: {
                lineStyle: {
                    color: '#289bd3',
                    width: 2
                }
            },
            axisLabel: {
                textStyle: {
                    fontSize: 14,
                    color: '#333'
                }
            },
            max: yMax
        },
        tooltip: {
            trigger: 'axis'
        },
        series: [{
            name: standardTitle + '数据',
            type: 'line',
            smooth: true,
            data: yData,
            itemStyle: {
                normal:{
                    color: '#2ec7c9'
                }

            },
            lineStyle:{
                width:5
            },
            markPoint: {
                itemStyle: {
                    normal:{
                        color: '#2ec7c9'
                    }

                },
                data: [{
                    type: 'max',
                    name: '最大值'
                }, {
                    type: 'min',
                    name: '最小值'
                }]
            },
            markLine: {
                data: [
                    {type: 'average', name: '平均值'}
                ]
            }
        }]
    };
    myChart1.setOption(option);
}

/**
 * 查询最大值
 * @param yData
 */
function findMaxYdata(yData) {
    var maxValue = 1;
    if(yData.length > 0){
        for(var i=0;i<yData.length;i++){
            if(null != yData[i] && "" != yData[i]){
                var ydata = parseFloat(yData[i]);
                if(ydata > maxValue){
                    maxValue = ydata;
                }
            }
        }
    }
    return maxValue;
}